package controller

import (
	"context"
	"fmt"
	"github.com/patrickmn/go-cache"
	"goods_user_srv/data_source"
	"goods_user_srv/models"
	front_user "goods_user_srv/proto/front_user"
	"goods_user_srv/utils"

	// "goods_user_srv/utils"

	// "goods_user_srv/utils"
	"time"
)

/*
定义一个和proto中与service同名的结构体
 */
type FrontUser struct {

}

var c = cache.New(time.Second * 30, time.Second * 60)

// 重写服务方法
func (f *FrontUser)FrontUserRegister(ctx context.Context, in *front_user.FrontUserRequest, out *front_user.FrontUserResponse) error {
	email := in.Email
	captcha := in.Code
	password := in.Password

	// log.Println(email, captcha, password)

	// 校验验证码
	// c := cache.New(time.Second * 30, time.Second * 60)
	//使用
	cacheEmail, ok := c.Get(email)
	fmt.Println(captcha, cacheEmail)
	if ok {  // 从缓存中取到了数据
		if captcha == cacheEmail {   // 验证码错误
			out.Code = 500
			out.Msg = "验证码错误"
		}else {   // 保存到数据库
			// 加密密码
			md5_password := utils.Md5pwd(password)

			front_user := models.User{
				Email:email,
				Password:md5_password,
				Status:1,
				CreateTime:time.Now(),
			}
			data_source.Db.Create(&front_user)

			out.Code = 200
			out.Msg = "注册成功，请登录"
		}
	}else {
		out.Code = 500
		out.Msg = "注册失败，请重新尝试"
	}

	// log.Println(email, password)
	return nil
}


// 重写发送邮件的方法
func (f *FrontUser)FrontUserEmail(ctx context.Context, in *front_user.FrontUserEmailRequest, out *front_user.FrontUserResponse) error {

	// 接收参数
	email := in.Email

	/*
	验证该用户是否注册过
	 */
	user := new(models.User)
	data_source.Db.Where("email = ?", email).First(user)
	if user.Email != "" {  // 用户已经注册
		out.Code = 500
		out.Msg = "用户已经注册过，请前往登陆页面"
	}else {
		// 生成6位数的验证码
		//randomNUm := utils.GenRandNum(6)
		// 消息内容
		//email_msg := fmt.Sprintf("您的注册验证码为：%s",randomNUm)
		// 发送邮件
		//utils.SendEmail(email, email_msg)

		/*
			缓存邮件和随机数
		*/
		// 使用go-cahe 缓存   "github.com/patrickmn/go-cache"
		// 初始化
		//c := cache.New(time.Second * 30, time.Second * 60)
		//使用
		c.Set(email, 111111, cache.DefaultExpiration)

		fmt.Println(c.Get(email))

		// 使用redis 缓存

		//fmt.Println(email)
		out.Code = 200
		out.Msg = "邮件发送成功"
	}
	return nil
}


// 重写登陆方法
func (f *FrontUser)FrontUserLogin(ctx context.Context,in *front_user.FrontUserLoginRequest,out *front_user.FrontUserResponse) error  {
	// 接收参数
	email := in.Email
	password := in.Password
	//fmt.Println(email, password)

	// 校验参数
	md5_password := utils.Md5pwd(password)
	// 从数据库取出数据
	user := new(models.User)
	data_source.Db.Where("email = ?", email).First(user)
	if user.Email != "" {
		if user.Password == md5_password {
			out.Code = 200
			out.Msg = "登陆成功"
			out.UserName = user.Email
		}else {
			out.Code = 500
			out.Msg = "密码错误"
		}
	}else {
		out.Code = 500
		out.Msg = "用户未注册，请先进行注册"
	}
	return nil
}